<template>
  <div style="width: 1200px;margin: 0 auto">

    <!--选择就诊人+添加就诊人信息-->
    <el-card>
      <!--选择就诊人-->
      <el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
        选择就诊人
      </el-button>

      <el-drawer
          title="选择就诊人"
          :visible.sync="drawer"
          size="60%">
        <div>

          <el-button @click="innerDrawer = true">添加就诊人</el-button>

          <!-- 循环生成卡片和选择按钮 -->
          <div v-for="(patient, index) in patients" :key="index">
            <el-card style="margin-top: 5px">
              <span style="float: left;margin: 0" :class="{ 'selected': selectedPatientIndex === index }">{{ patient.name }}</span>
              <span style="margin-left: 100px">{{ patient.phone }}</span>
              <el-button @click="selectPatient(index)"
                         style="margin-left: 100px;float: right; position: relative">选择</el-button>
            </el-card>
          </div>

          <el-button style="margin: 50px 0 0 0;" type="primary" @click="addSuccess" :disabled="!isPatientSelected">保存</el-button>

          <!--添加就诊人-->
          <el-drawer
              title="添加就诊人"
              :append-to-body="true"
              :before-close="handleClose"
              :visible.sync="innerDrawer"
              size="50%">

            <div style="margin: 20px;"></div>
            <!--就诊人详细信息-->

            <el-form :model="ruleForm1" :rules="userInfoRules" ref="ruleForm1" label-width="100px" class="demo-ruleForm">

              <el-form-item label="姓名" prop="name">
                <el-input v-model="ruleForm1.name" style="width: 300px;text-align: left;display: flex"></el-input>
              </el-form-item>

              <el-form-item label="身份证号" prop="number" >
                <el-input v-model="ruleForm1.number" style="width: 300px;text-align: left;display: flex"></el-input>
              </el-form-item>

              <el-form-item label="联系方式" prop="phone">
                <el-input v-model="ruleForm1.phone" style="width: 300px;text-align: left;display: flex"></el-input>
              </el-form-item>

              <el-form-item label="性别:">
                <el-select v-model="ruleForm1.gender" placeholder="请选择性别" style="width:300px;float: left">
                  <el-option label="男" value="1"></el-option>
                  <el-option label="女" value="2"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="基础病" prop="background_disease">
                <el-input v-model="ruleForm1.background_disease" style="width: 300px;text-align: left;display: flex"></el-input>
              </el-form-item>

              <el-form-item label="紧急联系人" prop="emergency_contact_phone" >
                <el-input v-model="ruleForm1.emergency_contact_phone" style="width: 300px;text-align: left;display: flex"></el-input>
              </el-form-item>

              <!--      <div class="block">-->
              <!--        <span class="demonstration">出生年月</span>-->
              <el-form-item label="出生年月">
                <el-date-picker
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    v-model="ruleForm1.birth"
                    type="date"
                    placeholder="选择日期" style="width: 300px;text-align: left;display: flex">
                </el-date-picker>
              </el-form-item>
              <!--      </div>-->

              <el-form-item label="省份" >
                <el-select v-model="ruleForm1.province" placeholder="请选择" style="width: 300px;text-align: left;display: flex">
                  <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="市" >
                <el-select v-model="ruleForm1.city" placeholder="请选择" style="width: 300px;text-align: left;display: flex">
                  <el-option
                      v-for="item in options1"
                      :key="item.value1"
                      :label="item.label1"
                      :value="item.label1" >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="区" >
                <el-select v-model="ruleForm1.area" placeholder="请选择" style="width: 300px;text-align: left;display: flex">
                  <el-option
                      v-for="item in options2"
                      :key="item.value1"
                      :label="item.label1"
                      :value="item.label1" >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="详细地址" prop="detail">
                <el-input v-model="ruleForm1.detail" style="width: 300px;text-align: left;display: flex"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="success" style="text-align: center;display: flex;"
                           @click="submitForm2('ruleForm1')" >保存信息</el-button>
              </el-form-item>

            </el-form>

          </el-drawer>
        </div>
      </el-drawer>


    </el-card>

    <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <!--项目内容：-->
      <el-card class="c3" style="height: 350px">

        <el-form-item label="请选择商品:" prop="goodsId" style="float:left;">
          <el-select v-model="ruleForm.goodsId" placeholder="请选择">
            <el-option v-for="item in goodsList" :label="item.goodsName" :value="item.id" ></el-option>
          </el-select>
        </el-form-item>
        <br><br><br>
        <el-form-item label="请选择陪诊员:" prop="staffId" style="position: absolute;margin-left: 14px">
          <el-select v-model="ruleForm.staffId" placeholder="请选择">
            <el-option v-for="item in patientsList" :label="item.username" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <br><br><br>
        <el-form-item label="支付渠道:" prop="getPayChannel" style="position: absolute;margin-left: 14px">
          <el-select v-model="ruleForm.getPayChannel" placeholder="请选择">
            <el-option label="支付宝支付" value="99"></el-option>
          </el-select>
        </el-form-item>


      </el-card>

      <!--价格+立即下单按钮-->
      <el-card>
        <el-form-item>
          <p style="float:left;color: red; margin-top: 40px">价格:￥{{ price }}</p>
          <el-button type="primary" @click="submitForm('ruleForm')" style="margin-top: 40px" :disabled="!isFormValid">确定</el-button>
          <el-button type="primary" @click="payClick('rule')" style="margin-top: 40px" >立即下单</el-button>
        </el-form-item>
      </el-card>
    </el-form>
  </div>

</template>
<script>
import TokenAxios from "@/http/TokenAxios";
import BaseUrl from "@/http/BaseUrl";

export default {
  data() {
    return {

      userInfoRules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        number: [
          { required: true, message:'身份证号码不能为空' },
          { validator: this.validateCardId, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' },
          { validator: this.validatePhone1, trigger: 'blur' }
        ],
        emergency_contact_phone: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' },
          { validator: this.validatePhone2, trigger: 'blur' }
        ],
        background_disease: [
          { required: true, message: '基础病不能为空', trigger: 'blur' },
          { validator: this.validateSort, trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '地址不能为空', trigger: 'blur' },
          { validator: this.validateSort2, trigger: 'blur' }
        ],
      },

      options2: [
        {
          value1: '选项1',
          label1: ' '
        },

      ],
      label2: '',
      options1: [{
        value1: '选项1',
        label1: '邯郸市'
      }, {
        value1: '选项2',
        label1: '秦皇岛市'
      }, {
        value1: '选项3',
        label1: '唐山市'
      }, {
        value1: '选项4',
        label1: '石家庄市'
      }, {
        value1: '选项5',
        label1: '张家口市'
      }, {
        value1: '选项6',
        label1: '邢台市'
      }, {
        value1: '选项7',
        label1: '保定市'
      }, {
        value1: '选项8',
        label1: '承德市'
      }, {
        value1: '选项9',
        label1: '沧州市'
      }, {
        value1: '选项10',
        label1: '廊坊市'
      }, {
        value1: '选项11',
        label1: '衡水市'
      }],
      label1: '',
      options: [{
        value: '选项1',
        label: '河北省'
      }],
      label: '',
      patients: [
        // 就诊人数据数组，用于循环生成卡片和选择按钮
      ],
      selectedPatientIndex: null,
      goodsList:[],
      patientsList:[],

    ruleForm1: {
      gender: '1', // 默认为男性，对应选项的值为 '1'

      name:'',
      number:'',
      phone:'',
      background_disease:'',
      emergency_contact_phone:'',
      detail:'',

      },
      textarea1: '',/*详细地址的*/
      gander: '1',/*就诊人性别*/
      labelPosition: 'left',/*添加就诊人那些向左对齐*/
      formLabelAlign: {/*就诊人详细信息*/
        name: '',
        number: '',
        phone: '',
        gander:'',
        textarea1:''
      },
      price: 358,/*价格*/
      ruleForm: {
        staffId:'',
        getPayChannel:'',
        goodsId:'',
        isFormValid: false,

      },

      isPayButtonEnabled: false,

      rule: {
        outTradeNo:'',
        subject:'陪诊服务',
        totalAmount:358,
      },

      drawer: false,/*选择就诊人*/
      innerDrawer: false,/*添加就诊人*/
    };
  },

  methods: {

    /*立即下单*/
    validateName(rule, value, callback) {
      const regex = /[\u4e00-\u9fa5a-zA-Z]+$/
      if (!value) {
        callback(new Error('姓名不能为空'));
      }else if (!regex.test(value)) {
        callback(new Error('姓名格式不正确'));
      } else {
        callback();
      }
    },
    validateCardId(rule, value, callback) {
      const regex = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
      if (!value) {
        callback(new Error('身份证号码不能为空'));
      } else if (!regex.test(value)) {
        callback(new Error('身份证号码格式不正确'));
      } else {
        callback();
      }
    },
    validatePhone1(rule, value, callback) {
      const regex = /^\d{11}$/;
      if (!value) {
        callback(new Error('电话号码号码不能为空'));
      } else if (!regex.test(value)) {
        callback(new Error('电话号码格式不正确'));
      } else {
        callback();
      }
    },
    validatePhone2(rule, value, callback) {
      const regex = /^\d{11}$/;
      if (!value) {
        callback(new Error('电话号码不能为空'));
      } else if (!regex.test(value)) {
        callback(new Error('电话号码格式不正确'));
      } else {
        callback();
      }
    },
    validateSort(rule, value, callback) {
      if (!value) {
        callback(new Error('病例不能为空'));
      } else {
        callback();
      }
    },
    validateSort2(rule, value, callback) {
      if (!value) {
        callback(new Error('地址不能为空'));
      } else {
        callback();
      }
    },
    submitForm2(ruleForm1) {
      this.$refs[ruleForm1].validate((valid) => {
        if (valid) {
          this.submitForm1()
        } else {
          this.$message({
            message: '请检查数据格式！',
            type: 'error'
          });
          return false;
        }
      });
    },

    submitForm1(formName1) {
      if (Array.isArray(this.ruleForm1.parentId)) {
        this.ruleForm1.parentId = this.ruleForm1.parentId.pop();
      }

          let url = BaseUrl.INFORMATIOON+'/patients/insert';
          console.log('url = ' + url);
          debugger
          TokenAxios.post(url, this.ruleForm1).then((response) => {
            let jsonResult = response.data;
            debugger
            if (jsonResult.state == 20000) {
              debugger
              this.$message({
                message: '添加就诊人成功！',
                type: 'success'
              });
              // this.resetForm(formName1);
              /*this.$router.push("/personal/client")*/
              TokenAxios.get(BaseUrl.INFORMATIOON+'/patients/').then((response) => {
                let jsonResult = response.data;
                if (jsonResult.state == 20000) {
                  this.patients=jsonResult.data
                }else{
                  this.$message.error(jsonResult.message);
                }
              });
            }
          });
    },
    generateRandomNum() {
      let randomNum = Math.floor(Math.random() * 1000000); // 生成一个六位数的随机数
      this.rule.outTradeNo = randomNum.toString(); // 将随机数转换为字符串并赋值给 outTradeNo 字段

    },

    submitForm(formName) {
      this.generateRandomNum();

      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          // let formData = this.qs.stringify(this.ruleForm);
          TokenAxios.post(BaseUrl.ORDER+'/orders/create', this.ruleForm).then((response) => {
            if (response.data.state == 20000) {
              this.$message({
                showClose: true,
                message: '数据已保存！',
                type: 'success',
              });
              this.ruleForm = response.data.data;
              this.resetForm(formName);
              this.isPayButtonEnabled = true;
            } else {
              this.$message("请勿重复点击确定！");
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    payClick(rule) {
      let url = BaseUrl.ORDER+'/alipay/pay';
      let params = {
        outTradeNo: this.rule.outTradeNo,
        subject: '订单支付',
        totalAmount: this.rule.totalAmount
      };

      TokenAxios.get(url, { params })
          .then(response => {
            if (response.data.state != 200) {
              this.$message({
                showClose: true,
                message: '正在跳转！',
                type: 'success'
              });
              window.open(url + '?' + this.qs.stringify(params));
            } else {
              this.$message.error(response.data.message);
            }
          })
          .catch(error => {
            console.error(error);
          });
    },

    selectPatient(index) {
      if (this.selectedPatientIndex === index) {
        this.selectedPatientIndex = null; // 点击已选中的按钮，取消选择
      } else {
        this.selectedPatientIndex = index; // 点击其他按钮，更新选择
      }
    },

    addSuccess() {
      if (this.isPatientSelected) {
        this.$message({
          showClose: true,
          message: '保存成功！',
          type: 'success'
        });
      } else {
        this.$message.error('请选择患者！');
      }
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    handleOutsideClick(event) {
      const target = event.target;
      const patientButtons = document.querySelectorAll('.el-button');
      const isPatientButton = Array.from(patientButtons).some(button => button.contains(target));
      if (!isPatientButton) {
        this.selectedPatientIndex = null;
      }
    },

  },
  mounted() {
    TokenAxios.get(BaseUrl.INFORMATIOON+'/patients/').then((response) => {
      let jsonResult = response.data;
      if (jsonResult.state == 20000) {
        this.patients=jsonResult.data
      }else{
        this.$message.error(jsonResult.message);
      }
    });

    TokenAxios.get(BaseUrl.GOODS+'/packages/admin').then((response)=>{
      let jsonResult = response.data;
      if (jsonResult.state == 20000) {
        this.goodsList=jsonResult.data
      }else{
        this.$message.error(jsonResult.message);
      }
    });

    TokenAxios.get(BaseUrl.STAFF_USER+'/staffs').then((response)=>{
      let jsonResult = response.data;
      if (jsonResult.state == 20000) {
        this.patientsList=jsonResult.data
      }else{
        this.$message.error(jsonResult.message);
      }
    });

    document.addEventListener('click', this.handleOutsideClick);

  },

  beforeUnmount() {
    document.removeEventListener('click', this.handleOutsideClick);
  },

  computed: {
    // 使用计算属性进行类型转换
    convertedValue() {
      return this.gender.toString();
    },

    // 计算属性，检查表单是否选择完整
    isFormValid() {
      return this.ruleForm.goodsId && this.ruleForm.staffId && this.ruleForm.getPayChannel;
    },

    isPatientSelected() {
      return this.selectedPatientIndex !== null;
    },

  },
}
</script>

<style scoped>

</style>
